package com.qingzhuge.file.service.cloud;

import com.qingzhuge.exception.ServiceException;
import com.qingzhuge.file.entity.FileStorageConfig;
import com.qingzhuge.file.service.BaseFileStorageService;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author : zero.xiao
 * @description : 七牛云存储
 * @date :2018/6/8 0008 下午 15:14
 * @since : 1.0.0
 * @modified :
 */
public class StorageQiniuCloudService extends BaseFileStorageService {
    private UploadManager uploadManager;
    private String token;

    StorageQiniuCloudService(FileStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }
    @Override
    protected String separator() {
        return PATH_SEPARATOR;
    }
    @Override
    protected String getPrefix() {
        return config.getQiniuPrefix();
    }

        private void init() {
            uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
                uploadToken(config.getQiniuBucketName());
    }

    @Override
    public String upload(byte[] data, String path) {
        if(!path.startsWith(File.separator)) {
            path = File.separator + path;
        }
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (java.lang.Exception e) {
            throw new ServiceException("上传文件失败，请核对七牛配置信息", e);
        }
        return config.getQiniuDomain() + File.separator + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new ServiceException("上传文件失败", e);
        }
    }

    @Override
    public void download(String path, OutputStream outputStream) {

    }

    @Override
    public void delete(String path) {

    }
}
